package cn.cxq;

import java.util.ArrayList;

/**
 * Hive工具类
 */
public class HiveSQLUtil {

    /**
     * 将表对象转换成Hive建表语句
     *
     * @param table        表对象
     * @param databaseName 数据库名称
     * @return Hive建表语句
     */
    public static String convertIntoHiveSQL(Table table, String databaseName) {
        StringBuffer buffer = new StringBuffer();

        buffer.append("drop table if exists " + databaseName + "." + table.getTableName() + ";\n" +
                "create table if not exists " + databaseName + "." + table.getTableName() + "\n" +
                "(\n");
        ArrayList<Table.Column> columns = table.getColumns();

        for (int i = 0; i < columns.size(); i++) {
            Table.Column column = columns.get(i);
            buffer.append(" " + column.columnName + " " + column.columnType + (column.columnComment == null ? "" : " comment '" + column.columnComment + "'"));
            if (i != columns.size() - 1) {
                buffer.append(",\n");
            }
        }

        buffer.append("\n)" +
                (table.getTableComment() == null ? "" : "comment " + table.getTableComment()) + "\n" +
                "row format delimited fields terminated by '\\001'\n" +
                "stored as parquet tblproperties ('orc.compress'='snappy');");

        return buffer.toString();
    }
}
